#include "./include/pthread_func.h"

void *pthread_udp_recv(void *args)
{
	int ret;
	char buffer[1024];
	struct networkindex *ni_obj = (struct networkindex *)args;
	struct sockaddr_in udp_recvaddr;
	socklen_t addr_len;
	addr_len = sizeof(struct sockaddr_in);
	while(1)
	{
		bzero(buffer, sizeof(buffer));
		ret = recvfrom(ni_obj->udp_socket, buffer, sizeof(buffer), 0, (struct sockaddr *)&udp_recvaddr, &addr_len);
		if(0 != ret)
		{
			pthread_mutex_lock(&ni_obj->rl_mutex);
			recvlist_add(&ni_obj->rl_head, buffer, sizeof(buffer), &udp_recvaddr);
			pthread_mutex_unlock(&ni_obj->rl_mutex);
		}
		usleep(300000);
	}
}

void *pthread_udp_send(void *args)
{
	int ret;
	struct networkindex *ni_obj = (struct networkindex *)args;
	struct sendlist *sl_tmp = NULL;
	while(1)
	{
		pthread_mutex_lock(&ni_obj->sl_mutex);
		ret = sendlist_getfrist(&ni_obj->sl_head, &sl_tmp);
		if(0 == ret)
		{
			sendto(ni_obj->udp_socket, sl_tmp->data, sizeof(sl_tmp->data), 0, (struct sockaddr *)&sl_tmp->sendaddr, (socklen_t)sizeof(struct sockaddr_in));
			sendlist_del(&sl_tmp->pointer);
		}
		pthread_mutex_unlock(&ni_obj->sl_mutex);
		usleep(300000);
	}
}

void *pthread_recvlist_operation(void *args)
{
	int ret;
	char buf[1024];
	struct networkindex *ni_obj = (struct networkindex *)args;
	struct recvlist *rl_tmp = NULL;
	while(1)
	{
		pthread_mutex_lock(&ni_obj->rl_mutex);
		ret = recvlist_getfrist(&ni_obj->rl_head, &rl_tmp);
		if(0 == ret)
		{
			pthread_mutex_lock(&ni_obj->sl_mutex);
			sendlist_add(&ni_obj->sl_head, rl_tmp->data, sizeof(buf), &rl_tmp->recvaddr);
			recvlist_del(&rl_tmp->pointer);
			pthread_mutex_unlock(&ni_obj->sl_mutex);
		}
		pthread_mutex_unlock(&ni_obj->rl_mutex);
		usleep(300000);
	}
	return (void *)0;
}